package com.lightsaber.trade.as.web.device;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springside.modules.orm.Page;

import com.lightsaber.trade.as.entity.device.Device;
import com.lightsaber.trade.as.service.device.DeviceManager;
import com.lightsaber.trade.core.entity.BaseEntity;
import com.lightsaber.trade.core.web.BaseAction;

@Namespace("/device")
public class DeviceAction extends BaseAction {

    @Autowired
    private transient DeviceManager deviceManager;

    private Device device = new Device();// As same as ActionForm

    @Value(value = "#{appProperties['device.page.size']}")
    private String PAGE_SIZE;

    private Page<Device> page;

    boolean clear;

    @Override
    public String execute() throws Exception {
        return list();
    }

    public String list() {
        if (clear) {
            device = new Device();
            return SUCCESS;
        }

        if (page == null) {
            page = new Page<Device>(Integer.valueOf(PAGE_SIZE));
        } else {
            page.setPageSize(Integer.valueOf(PAGE_SIZE));
        }

        if (!page.isOrderBySetted()) {
            page.setOrderBy(BaseEntity.ID);
            page.setOrder(Page.ASC);
        }

        deviceManager.findPage(device, page);

        return SUCCESS;
    }

    public String input() {
        if (StringUtils.isNotBlank(device.getId())) {

            device = deviceManager.get(device.getId());
        }

        return INPUT;
    }

    public String save() {

        deviceManager.save(device);

        return INPUT;
    }

    public String delete() {

        deviceManager.delete(device.getId());

        device = new Device();
        return list();
    }

    public Device getDevice() {
        return device;
    }

    public void setDevice(Device device) {
        this.device = device;
    }

    public Page<Device> getPage() {
        return page;
    }

    public void setPage(Page<Device> page) {
        this.page = page;
    }

    public boolean isClear() {
        return clear;
    }

    public void setClear(boolean clear) {
        this.clear = clear;
    }
}
